#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
股票分析Flask API服务器
提供MACD和RSI分析的RESTful API接口
"""

from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from stock_analyzer import StockAnalyzer
import traceback
import logging
import os
import glob
from datetime import datetime

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
# 启用CORS以支持前端调用
CORS(app, origins=[
    "http://localhost:3000", 
    "http://127.0.0.1:3000",
    "https://lnuyasha.com",
    "http://lnuyasha.com"
])

@app.route('/', methods=['GET'])
def home():
    """
    API首页 - 返回服务信息
    """
    return jsonify({
        'status': 'success',
        'message': '股票MACD和RSI分析API服务',
        'version': '1.0.0',
        'endpoints': {
            'analyze': '/api/analyze/<symbol>',
            'enhanced_analyze': '/api/enhanced-analyze/<symbol>',
            'health': '/api/health',
            'latest_report_info': '/api/latest-report-info',
            'download_latest_report': '/api/download-latest-report'
        }
    })

@app.route('/api/health', methods=['GET'])
def health_check():
    """
    健康检查接口
    """
    return jsonify({
        'status': 'healthy',
        'message': 'API服务运行正常'
    })

@app.route('/api/download-latest-report', methods=['GET'])
def download_latest_report():
    """
    下载最新的分析报告
    
    Returns:
    最新日期的TXT报告文件
    """
    try:
        # 报告目录路径
        result_dir = '/home/Test/result'
        
        # 检查目录是否存在
        if not os.path.exists(result_dir):
            return jsonify({
                'status': 'error',
                'message': '报告目录不存在',
                'error_code': 'DIRECTORY_NOT_FOUND'
            }), 404
        
        # 查找所有的TXT文件
        pattern = os.path.join(result_dir, '*.txt')
        md_files = glob.glob(pattern)
        
        if not md_files:
            return jsonify({
                'status': 'error',
                'message': '没有找到任何报告文件',
                'error_code': 'NO_REPORTS_FOUND'
            }), 404
        
        # 按文件名排序（日期格式YYYYMMDD.txt），获取最新的
        md_files.sort(reverse=True)
        latest_file = md_files[0]
        
        # 提取文件名（不含路径）
        filename = os.path.basename(latest_file)
        
        # 检查文件是否存在且可读
        if not os.path.exists(latest_file):
            return jsonify({
                'status': 'error',
                'message': f'报告文件 {filename} 不存在',
                'error_code': 'FILE_NOT_FOUND'
            }), 404
        
        logger.info(f"正在提供最新报告下载: {filename}")
        
        # 发送文件
        return send_file(
            latest_file,
            as_attachment=True,
            download_name=f"股票分析报告_{filename}",
            mimetype='text/plain'
        )
        
    except Exception as e:
        logger.error(f"下载报告时发生错误: {str(e)}")
        logger.error(traceback.format_exc())
        
        return jsonify({
            'status': 'error',
            'message': f'下载失败: {str(e)}',
            'error_code': 'DOWNLOAD_ERROR'
        }), 500

@app.route('/api/latest-report-info', methods=['GET'])
def get_latest_report_info():
    """
    获取最新报告的信息（不下载文件）
    
    Returns:
    最新报告的基本信息
    """
    try:
        # 报告目录路径
        result_dir = '/home/Test/result'
        
        # 检查目录是否存在
        if not os.path.exists(result_dir):
            return jsonify({
                'status': 'error',
                'message': '报告目录不存在',
                'error_code': 'DIRECTORY_NOT_FOUND'
            }), 404
        
        # 查找所有的TXT文件
        pattern = os.path.join(result_dir, '*.txt')
        md_files = glob.glob(pattern)
        
        if not md_files:
            return jsonify({
                'status': 'error',
                'message': '没有找到任何报告文件',
                'error_code': 'NO_REPORTS_FOUND'
            }), 404
        
        # 按文件名排序（日期格式YYYYMMDD.txt），获取最新的
        md_files.sort(reverse=True)
        latest_file = md_files[0]
        
        # 提取文件名和基本信息
        filename = os.path.basename(latest_file)
        file_size = os.path.getsize(latest_file)
        file_mtime = os.path.getmtime(latest_file)
        
        # 解析日期（从文件名中提取）
        date_str = filename.replace('.txt', '')
        try:
            report_date = datetime.strptime(date_str, '%Y%m%d').strftime('%Y-%m-%d')
        except ValueError:
            report_date = date_str
        
        return jsonify({
            'status': 'success',
            'data': {
                'filename': filename,
                'report_date': report_date,
                'file_size': file_size,
                'file_size_kb': round(file_size / 1024, 1),
                'last_modified': datetime.fromtimestamp(file_mtime).strftime('%Y-%m-%d %H:%M:%S'),
                'download_url': '/api/download-latest-report'
            }
        })
        
    except Exception as e:
        logger.error(f"获取报告信息时发生错误: {str(e)}")
        
        return jsonify({
            'status': 'error',
            'message': f'获取报告信息失败: {str(e)}',
            'error_code': 'INFO_ERROR'
        }), 500

@app.route('/api/enhanced-analyze/<symbol>', methods=['GET'])
def enhanced_analyze_stock(symbol):
    """
    增强股票分析接口 - 提供优化的评分算法、胜率预测、持仓比例和持有时间建议
    
    Parameters:
    - symbol: 股票代码 (路径参数)
    - period: 分析周期 (查询参数，可选，默认6mo)
    
    Returns:
    JSON格式的增强分析结果
    """
    try:
        # 获取查询参数
        period = request.args.get('period', '6mo')
        
        logger.info(f"开始增强分析股票: {symbol}, 周期: {period}")
        
        # 创建分析器
        analyzer = StockAnalyzer(symbol, period=period)
        
        # 获取数据
        if not analyzer.fetch_data():
            return jsonify({
                'status': 'error',
                'message': f'无法获取股票 {symbol} 的数据',
                'error_code': 'DATA_FETCH_FAILED'
            }), 400
        
        # 计算指标
        if not analyzer.calculate_macd():
            return jsonify({
                'status': 'error',
                'message': 'MACD计算失败',
                'error_code': 'MACD_CALCULATION_FAILED'
            }), 500
        
        if not analyzer.calculate_rsi():
            return jsonify({
                'status': 'error',
                'message': 'RSI计算失败',
                'error_code': 'RSI_CALCULATION_FAILED'
            }), 500
        
        # 获取增强投资分析
        enhanced_analysis = analyzer.get_enhanced_investment_analysis()
        
        if not enhanced_analysis:
            return jsonify({
                'status': 'error',
                'message': '无法获取增强分析数据',
                'error_code': 'ENHANCED_ANALYSIS_FAILED'
            }), 500
        
        # 获取基础数据
        macd_info = analyzer.detect_macd_crossover()
        rsi_info = analyzer.get_rsi_status()
        
        # 获取股价信息
        latest_price = float(analyzer.data['Close'].iloc[-1])
        price_change = float(analyzer.data['Close'].iloc[-1] - analyzer.data['Close'].iloc[-2])
        price_change_pct = (price_change / analyzer.data['Close'].iloc[-2]) * 100
        
        # 构建增强响应数据
        result = {
            'status': 'success',
            'data': {
                'symbol': analyzer.symbol,
                'period': period,
                'analysis_date': analyzer.data.index[-1].strftime('%Y-%m-%d'),
                'data_points': len(analyzer.data),
                'price_info': {
                    'current_price': round(latest_price, 2),
                    'price_change': round(price_change, 2),
                    'price_change_percent': round(price_change_pct, 2)
                },
                # 增强投资建议
                'enhanced_recommendation': {
                    'action': enhanced_analysis['action'],
                    'action_text': enhanced_analysis['action_text'],
                    'total_score': enhanced_analysis['total_score'],
                    'win_probability': enhanced_analysis['win_probability'],
                    'position_ratio': enhanced_analysis['position_ratio'],
                    'hold_period': enhanced_analysis['hold_period'],
                    'risk_level': enhanced_analysis['risk_level'],
                    'analysis_details': enhanced_analysis['analysis_details']
                },
                # 详细评分（优化版 - 反映新的权重结构）
                'detailed_scores': {
                    'macd_score': round(enhanced_analysis['detailed_scores']['macd_score'], 1),
                    'rsi_score': round(enhanced_analysis['detailed_scores']['rsi_score'], 1),
                    'trend_score': round(enhanced_analysis['detailed_scores']['trend_score'], 1),
                    'momentum_score': round(enhanced_analysis['detailed_scores']['momentum_score'], 1),
                    'volatility_score': round(enhanced_analysis['detailed_scores']['volatility_score'], 1),
                    'drawdown_risk_score': round(enhanced_analysis['detailed_scores'].get('drawdown_risk_score', 50), 1),  # 新增回撤风险评分
                    'support_resistance_score': round(enhanced_analysis['detailed_scores']['support_resistance_score'], 1),
                    'market_environment_score': round(enhanced_analysis['detailed_scores']['market_environment_score'], 1),
                    'valuation_score': round(enhanced_analysis['detailed_scores']['valuation_score'], 1),
                    'death_to_golden_bonus': round(enhanced_analysis['detailed_scores'].get('death_to_golden_bonus', 0), 1)  # 新增死叉到金叉奖励分数
                },
                # MACD分析（兼容现有前端，优化逻辑）
                'macd_analysis': {
                    'golden_cross_detected': bool(macd_info['golden_cross']['detected']),
                    'golden_cross_date': macd_info['golden_cross']['date'].strftime('%Y-%m-%d') if macd_info['golden_cross']['detected'] else None,
                    'death_cross_detected': bool(macd_info['death_cross']['detected']),
                    'death_cross_date': macd_info['death_cross']['date'].strftime('%Y-%m-%d') if macd_info['death_cross']['detected'] else None,
                    'current_macd': round(macd_info['current_macd'], 4),
                    'current_signal': round(macd_info['current_signal'], 4),
                    'current_histogram': round(macd_info['current_histogram'], 4),
                    'quality': macd_info['quality'],
                    'quality_score': round(macd_info['quality_score'], 1),
                    'position_score': round(macd_info['position_score'], 1),
                    'resonance_score': round(macd_info['resonance_score'], 1),
                    'volume_score': round(macd_info['volume_score'], 1),
                    'timeliness_score': round(macd_info['timeliness_score'], 1),
                    # 死叉风险信息
                    'death_cross_risk_level': macd_info['death_cross']['risk_level'] if macd_info['death_cross']['detected'] else None,
                    'death_cross_risk_score': round(macd_info['death_cross']['risk_score'], 1) if macd_info['death_cross']['detected'] else 0,
                    'position_risk': round(macd_info['death_cross']['position_risk'], 1) if macd_info['death_cross']['detected'] else 0,
                    'momentum_risk': round(macd_info['death_cross']['momentum_risk'], 1) if macd_info['death_cross']['detected'] else 0,
                    'volume_risk': round(macd_info['death_cross']['volume_risk'], 1) if macd_info['death_cross']['detected'] else 0,
                    'timeliness_risk': round(macd_info['death_cross']['timeliness_risk'], 1) if macd_info['death_cross']['detected'] else 0,
                    # 新增：死叉转金叉奖励信息
                    'death_to_golden_transition': {
                        'is_transitioning': bool(not macd_info['golden_cross']['detected'] and not macd_info['death_cross']['detected'] and macd_info['current_macd'] < macd_info['current_signal']),
                        'transition_bonus_score': round(enhanced_analysis['detailed_scores'].get('death_to_golden_bonus', 0), 1),
                        'macd_signal_distance': round(abs(macd_info['current_macd'] - macd_info['current_signal']), 4),
                        'histogram_trend': 'improving' if len(analyzer.macd_data) >= 2 and analyzer.macd_data['Histogram'].iloc[-1] > analyzer.macd_data['Histogram'].iloc[-2] else 'declining'
                    },
                    # 交叉状态说明（确保金叉和死叉不会同时为true）
                    'crossover_status': {
                        'most_recent_signal': 'golden_cross' if macd_info['golden_cross']['detected'] else 'death_cross' if macd_info['death_cross']['detected'] else 'none',
                        'signal_priority_note': '金叉和死叉不会同时检测为true，优先显示最近的信号'
                    }
                },
                # RSI分析（兼容现有前端）
                'rsi_analysis': {
                    'current_rsi': round(rsi_info['value'], 2),
                    'status': rsi_info['status'],
                    'advice': rsi_info['advice'],
                    'risk_level': 'high' if rsi_info['status'] == '超买' else 'low' if rsi_info['status'] == '超卖' else 'medium'
                },
                # 传统建议（兼容现有前端）
                'recommendation': {
                    'action': enhanced_analysis['action'],
                    'text': enhanced_analysis['action_text'],
                    'full_analysis': enhanced_analysis['analysis_details']
                }
            }
        }
        
        logger.info(f"股票 {symbol} 增强分析完成，总评分: {enhanced_analysis['total_score']}, 胜率: {enhanced_analysis['win_probability']}%")
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"增强分析股票 {symbol} 时发生错误: {str(e)}")
        logger.error(traceback.format_exc())
        
        return jsonify({
            'status': 'error',
            'message': f'增强分析过程中发生错误: {str(e)}',
            'error_code': 'ENHANCED_ANALYSIS_ERROR'
        }), 500

@app.route('/api/analyze/<symbol>', methods=['GET'])
def analyze_stock(symbol):
    """
    股票分析接口
    
    Parameters:
    - symbol: 股票代码 (路径参数)
    - period: 分析周期 (查询参数，可选，默认6mo)
    
    Returns:
    JSON格式的分析结果
    """
    try:
        # 获取查询参数
        period = request.args.get('period', '6mo')
        
        logger.info(f"开始分析股票: {symbol}, 周期: {period}")
        
        # 创建分析器
        analyzer = StockAnalyzer(symbol, period=period)
        
        # 获取数据
        if not analyzer.fetch_data():
            return jsonify({
                'status': 'error',
                'message': f'无法获取股票 {symbol} 的数据',
                'error_code': 'DATA_FETCH_FAILED'
            }), 400
        
        # 计算指标
        if not analyzer.calculate_macd():
            return jsonify({
                'status': 'error',
                'message': 'MACD计算失败',
                'error_code': 'MACD_CALCULATION_FAILED'
            }), 500
        
        if not analyzer.calculate_rsi():
            return jsonify({
                'status': 'error',
                'message': 'RSI计算失败',
                'error_code': 'RSI_CALCULATION_FAILED'
            }), 500
        
        # 获取分析结果
        macd_info = analyzer.detect_macd_crossover()
        rsi_info = analyzer.get_rsi_status()
        
        if not macd_info or not rsi_info:
            return jsonify({
                'status': 'error',
                'message': '无法获取完整的分析数据',
                'error_code': 'ANALYSIS_INCOMPLETE'
            }), 500
        
        # 生成综合建议 - 基于高胜率MACD金叉原则
        suggestion_text = analyzer.get_investment_suggestion()
        
        # 获取股价信息
        latest_price = float(analyzer.data['Close'].iloc[-1])
        price_change = float(analyzer.data['Close'].iloc[-1] - analyzer.data['Close'].iloc[-2])
        price_change_pct = (price_change / analyzer.data['Close'].iloc[-2]) * 100
        
        # 生成智能投资建议 - 基于新的质量评估
        if macd_info['death_cross']['detected'] and macd_info['death_cross']['risk_level'] == 'high':
            recommendation = "sell"
            recommendation_text = "强烈建议卖出"
        elif macd_info['death_cross']['detected'] and macd_info['death_cross']['risk_level'] == 'medium':
            recommendation = "cautious_sell"
            recommendation_text = "建议减仓"
        elif macd_info['golden_cross']['detected']:
            if macd_info['golden_cross']['quality'] == 'high':
                if rsi_info['status'] != "超买":
                    recommendation = "strong_buy"
                    recommendation_text = "强烈推荐买入"
                else:
                    recommendation = "cautious_buy"
                    recommendation_text = "谨慎买入"
            elif macd_info['golden_cross']['quality'] == 'medium':
                if rsi_info['status'] == "超卖":
                    recommendation = "moderate_buy"
                    recommendation_text = "适度买入"
                elif rsi_info['status'] != "超买":
                    recommendation = "cautious"
                    recommendation_text = "谨慎参与"
                else:
                    recommendation = "hold"
                    recommendation_text = "建议观望"
            else:  # low quality
                recommendation = "avoid"
                recommendation_text = "不建议买入"
        else:
            if rsi_info['status'] == "超卖":
                recommendation = "consider_buy"
                recommendation_text = "考虑分批买入"
            elif rsi_info['status'] == "超买":
                recommendation = "sell"
                recommendation_text = "建议卖出"
            else:
                recommendation = "hold"
                recommendation_text = "建议观望"
        
        # 构建响应数据
        result = {
            'status': 'success',
            'data': {
                'symbol': analyzer.symbol,
                'period': period,
                'analysis_date': analyzer.data.index[-1].strftime('%Y-%m-%d'),
                'data_points': len(analyzer.data),
                'price_info': {
                    'current_price': round(latest_price, 2),
                    'price_change': round(price_change, 2),
                    'price_change_percent': round(price_change_pct, 2)
                },
                'macd_analysis': {
                    'golden_cross_detected': macd_info['golden_cross']['detected'],
                    'golden_cross_date': macd_info['golden_cross']['date'].strftime('%Y-%m-%d') if macd_info['golden_cross']['detected'] else None,
                    'death_cross_detected': macd_info['death_cross']['detected'],
                    'death_cross_date': macd_info['death_cross']['date'].strftime('%Y-%m-%d') if macd_info['death_cross']['detected'] else None,
                    'current_macd': round(macd_info['current_macd'], 4),
                    'current_signal': round(macd_info['current_signal'], 4),
                    'current_histogram': round(macd_info['current_histogram'], 4),
                    'quality': macd_info['quality'],
                    'quality_score': round(macd_info['quality_score'], 1),
                    'position_score': round(macd_info['position_score'], 1),
                    'resonance_score': round(macd_info['resonance_score'], 1),
                    'volume_score': round(macd_info['volume_score'], 1),
                    'timeliness_score': round(macd_info['timeliness_score'], 1),
                    'death_cross_risk_level': macd_info['death_cross']['risk_level'] if macd_info['death_cross']['detected'] else None,
                    'death_cross_risk_score': round(macd_info['death_cross']['risk_score'], 1) if macd_info['death_cross']['detected'] else 0,
                    'position_risk': round(macd_info['death_cross']['position_risk'], 1) if macd_info['death_cross']['detected'] else 0,
                    'momentum_risk': round(macd_info['death_cross']['momentum_risk'], 1) if macd_info['death_cross']['detected'] else 0,
                    'volume_risk': round(macd_info['death_cross']['volume_risk'], 1) if macd_info['death_cross']['detected'] else 0,
                    'timeliness_risk': round(macd_info['death_cross']['timeliness_risk'], 1) if macd_info['death_cross']['detected'] else 0,
                    'macd_strength': 'strong' if abs(macd_info['current_macd']) > 2 else 'medium' if abs(macd_info['current_macd']) > 0.5 else 'weak'
                },
                'rsi_analysis': {
                    'current_rsi': round(rsi_info['value'], 2),
                    'status': rsi_info['status'],
                    'advice': rsi_info['advice'],
                    'risk_level': 'high' if rsi_info['status'] == '超买' else 'low' if rsi_info['status'] == '超卖' else 'medium'
                },
                'recommendation': {
                    'action': recommendation,
                    'text': recommendation_text,
                    'full_analysis': suggestion_text
                }
            }
        }
        
        logger.info(f"股票 {symbol} 分析完成")
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"分析股票 {symbol} 时发生错误: {str(e)}")
        logger.error(traceback.format_exc())
        
        return jsonify({
            'status': 'error',
            'message': f'分析过程中发生错误: {str(e)}',
            'error_code': 'INTERNAL_ERROR'
        }), 500

@app.route('/api/analyze', methods=['POST'])
def analyze_stock_post():
    """
    POST方式的股票分析接口
    
    Request Body:
    {
        "symbol": "股票代码",
        "period": "分析周期" (可选)
    }
    """
    try:
        data = request.get_json()
        
        if not data or 'symbol' not in data:
            return jsonify({
                'status': 'error',
                'message': '请提供股票代码',
                'error_code': 'MISSING_SYMBOL'
            }), 400
        
        symbol = data['symbol']
        period = data.get('period', '6mo')
        
        # 重定向到GET接口的逻辑
        return analyze_stock(symbol)
        
    except Exception as e:
        logger.error(f"POST分析请求处理错误: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': f'请求处理错误: {str(e)}',
            'error_code': 'REQUEST_ERROR'
        }), 400

@app.errorhandler(404)
def not_found(error):
    """
    404错误处理
    """
    return jsonify({
        'status': 'error',
        'message': '请求的API端点不存在',
        'error_code': 'NOT_FOUND'
    }), 404

@app.errorhandler(500)
def internal_error(error):
    """
    500错误处理
    """
    return jsonify({
        'status': 'error',
        'message': '服务器内部错误',
        'error_code': 'INTERNAL_SERVER_ERROR'
    }), 500

if __name__ == '__main__':
    print("🚀 启动股票分析API服务器...")
    print("📊 API端点:")
    print("   - GET  /                            - 服务信息")
    print("   - GET  /api/health                  - 健康检查") 
    print("   - GET  /api/analyze/<symbol>        - 股票分析")
    print("   - POST /api/analyze                 - 股票分析(POST)")
    print("   - GET  /api/enhanced-analyze/<symbol> - 增强分析")
    print("   - GET  /api/latest-report-info      - 最新报告信息")
    print("   - GET  /api/download-latest-report  - 下载最新报告")
    print("\n💡 示例请求:")
    print("   curl http://localhost:5001/api/analyze/AAPL")
    print("   curl http://localhost:5001/api/enhanced-analyze/AAPL")
    print("   curl http://localhost:5001/api/analyze/002405.SZ?period=3mo")
    print("\n🌐 服务器将在 http://localhost:5001 启动")
    print("\n✅ 已修复 market_environment_score 字段缺失的bug")
    
    # 开发模式运行
    app.run(host='0.0.0.0', port=5001, debug=True)